package com.yao.koin.api

import com.yao.koin.bean.Banner
import com.yao.koin.bean.BannerChild
import com.yao.koin.bean.DataX
import com.yao.koin.bean.GrilParent
import kotlinx.coroutines.coroutineScope
import java.io.IOException
import kotlinx.coroutines.CoroutineScope
import com.yao.koin.util.Result

open class BaseRepository {



    suspend fun <T : Any> safeApiCall(call: suspend () -> Result<T>, errorMessage: String): Result<T> {
        return try {
            call()
        } catch (e: Exception) {
            // An exception was thrown when calling the API so we're converting this to an IOException
            Result.Error(IOException(errorMessage, e))
        }
    }



    suspend fun <T : Any> executeResponse(response: GrilParent<T>, successBlock: (suspend CoroutineScope.() -> Unit)? = null,
                                          errorBlock: (suspend CoroutineScope.() -> Unit)? = null): Result<List<DataX>> {
        return coroutineScope {
            if (response.status == 100) {
                successBlock?.let { it() }
                Result.Success(response.data)
            } else {
                errorBlock?.let { it() }
                Result.Error(IOException(response.status.toString()))
            }
        }
    }



    suspend fun <T : Any> executeResponseBanner(response: Banner<T>, successBlock: (suspend CoroutineScope.() -> Unit)? = null,
                                          errorBlock: (suspend CoroutineScope.() -> Unit)? = null): Result<List<BannerChild>> {
        return coroutineScope {
            if (response.status == 100) {
                successBlock?.let { it() }
                Result.Success(response.data)
            } else {
                errorBlock?.let { it() }
                Result.Error(IOException(response.status.toString()))
            }
        }
    }


}